package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据id查询商品信息
     *
     * @param id
     * @return
     */

    @Override
    public Result queryShopById(Long id) {
        //1.缓存穿透
//        Shop shop = queryWithPassThrough(id);
        //2.缓存击穿
        //Shop shop = queryMutex(id);
        //3.逻辑过期
        Shop shop = setLogicTime(id);
        //4.返回信息
        return Result.ok(shop);
    }

    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期
     *
     * @param id
     * @return
     */
    public Shop setLogicTime(Long id) {
        //1根据id查询redis缓存商品信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.未查到信息直接返回
        if (StrUtil.isBlank(shopJson)) {
            //转换类型
            return null;

        }
        //3.查到信息
        //反序列化数据
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        //4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.未过期返回店铺信息
            return shop;
        }
        //6.过期尝试获取锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean flog = tryLock(lockKey);
        if (flog) {

            //7.获取到锁 开启新线程
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //7.1独立线程重构数据 查询数据库 写入redis
                    this.saveShop2Redis(id, LOCK_SHOP_TTL);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //7.2释放互斥锁
                    unlock(lockKey);
                }
            });
        }
        //8.返回过期数据
        return shop;

    }

    /**
     * 缓存击穿
     *
     * @param id
     * @return
     */
    public Shop queryMutex(Long id) {
        //1根据id查询redis缓存商品信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.查到信息 返回
        if (StrUtil.isNotBlank(shopJson)) {
            //转换类型
            return JSONUtil.toBean(shopJson, Shop.class);

        }
        //当前查到的是返回的空数据(防止内存穿透)
        if (shopJson != null) {
            return null;
        }
        //3.根据id到数据库查询
        Shop shop = getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //4.查询到的缓存到redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //5.返回信息
        return shop;
    }

    /**
     * 缓存穿透
     *
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id) {
        //1根据id查询redis缓存商品信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.查到信息 返回
        if (StrUtil.isNotBlank(shopJson)) {
            //转换类型
            return JSONUtil.toBean(shopJson, Shop.class);

        }
        //3判断命中的是否是空值
        if (shopJson != null) {
            return null;
        }
        //4获取锁
        Shop shop = null;
        try {
            boolean flog = tryLock(LOCK_SHOP_KEY + id);
            if (!flog) {
                Thread.sleep(50);
                return queryWithPassThrough(id);
            }
            //5.根据id到数据库查询\
            //二次判断
            shopJson = stringRedisTemplate.opsForValue().get(key);
            //2.查到信息 返回
            if (StrUtil.isNotBlank(shopJson)) {
                //转换类型
                return JSONUtil.toBean(shopJson, Shop.class);

            }
            //3判断命中的是否是空值
            if (shopJson != null) {
                return null;
            }
            shop = getById(id);
            Thread.sleep(200);
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6.查询到的缓存到redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7释放锁
            unlock(LOCK_SHOP_KEY + id);
        }

        //8.返回信息
        return shop;
    }

    /**
     * 获取锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }


    /**
     * 更新商铺信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
    //查询商铺
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
       //1.判断是否要根据坐标查询
        if(x== null  || y == null){
            Page<Shop> page = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3.查询redis,安装距离排序，分页
        String key = SHOP_GEO_KEY +typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        //解析id
        if(results == null){
            //没有查到数据 直接返回空
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        List<Long> ids = new ArrayList<>(list.size());
        if(list.size() < from){
            //总长度不大于需要跳过的数据
            return Result.ok(Collections.emptyList());
        }
        Map<String,Distance> distanceMap = new HashMap<>(list.size());

        list.stream().skip(from).forEach(result ->{
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }

    //保存店铺信息
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //1.查询店铺信息
        Shop shop = getById(id);
        Thread.sleep(200);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }
}
